package com.jbwz.web.security.controller;

import com.jbwz.web.common.base.BaseController;
import com.jbwz.web.common.base.BasePage;
import com.jbwz.web.common.base.IBasePage;
import com.jbwz.web.common.res.ResponseJson;
import com.jbwz.web.common.session.SecurityUserHolder;
import com.jbwz.web.security.entity.User;
import com.jbwz.web.security.entity.vo.UserVO;
import com.jbwz.web.security.service.UserRoleService;
import com.jbwz.web.security.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户 前端控制器
 *
 * @author yyh
 * @since 2021-07-16 23:46:06
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

  @Autowired UserService userService;
  @Autowired PasswordEncoder passwordEncoder;
  @Autowired private UserRoleService userRoleService;

  @GetMapping("/page-list")
  public ResponseJson pageList(BasePage page, UserVO vo) {
    IBasePage result = userService.pageList(page, vo);
    return success(result);
  }

  @PostMapping("/save")
  public ResponseJson save(@RequestBody @Validated UserVO vo) {
    userService.saveOrUpdateVO(vo);
    return success();
  }

  // 修改密码
  @PostMapping("/cg-pwd")
  public ResponseJson changePwd(@RequestBody UserVO vo) {
    return success();
  }

  @GetMapping("/del/{id}")
  public ResponseJson del(@PathVariable("id") Long id) {
    userService.removeByIdCheck(id);
    return success();
  }

  @GetMapping("/detail/{id}")
  public ResponseJson detail(@PathVariable("id") Long id) {
    User et = userService.getById(id);
    List<Long> roleIds = userRoleService.getByUserId(id);
    UserVO vo = toVO(et);
    vo.setRoleIds(roleIds);
    return success(vo);
  }

  @GetMapping("/current-user")
  public ResponseJson currentUser() {
    User et = userService.getById(SecurityUserHolder.getCurrentUserId());
    return success(toVO(et));
  }

  private UserVO toVO(User user) {
    UserVO vo = new UserVO();
    BeanUtils.copyProperties(user, vo);
    vo.setPassword(null);
    return vo;
  }

  @GetMapping("/pkeys")
  public ResponseJson pkeys() {
    return success(new ArrayList<>(userService.getCurrentUserPKey()));
  }
}
